package com.vdongchina.thread.base.demo.threadpool;

import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.atomic.AtomicLong;

public class DefaultThreadPool<Job extends Runnable> implements ThreadPool<Job> {

    //线程池最大限制数
    private static final int MAX_WORKER_NUMBERS = 10;

    //线程池默认的数量
    private static final int DEFAULT_WORKDER_NUBERS = 5;

    //线程池最小的数量
    private static final int MIN_WORKER_NUMBERS = 1;

    //工作者线程的数量
    private int workerNum = DEFAULT_WORKDER_NUBERS;

    //线程号生成
    private AtomicLong threadNum = new AtomicLong();

    /**
     * 工作列表
     */
    private final LinkedList<Job> jobs = new LinkedList<>();

    /**
     * 工作者列表
     * 这里的new是线程安全的
     */
    private final List<Worker> workers = Collections.synchronizedList(new ArrayList<>());


    public DefaultThreadPool() {

        initializeWokers(DEFAULT_WORKDER_NUBERS);
    }


    public DefaultThreadPool(int num) {
        this.workerNum = num > MAX_WORKER_NUMBERS?MAX_WORKER_NUMBERS:num<MIN_WORKER_NUMBERS?MIN_WORKER_NUMBERS:num;
        initializeWokers(num);
    }

    @Override
    public void execute(Job job) {
        if (job != null) {
            //添加工作者,然后唤醒
            synchronized (jobs) {
                jobs.addLast(job);
                jobs.notify();
            }
        }

    }

    @Override
    public void shutdown() {
        for (Worker worker : workers) {
            worker.shutdown();
        }
    }

    @Override
    public void addWorkers(int num) {
        synchronized (jobs) {
            //限制新增的worker数量不能超过最大值
            if (num + this.workerNum > MAX_WORKER_NUMBERS) {
                num = MAX_WORKER_NUMBERS - this.workerNum;
            }
            initializeWokers(num);
            this.workerNum += num;
        }
    }

    //初始化工作者线程
    private void initializeWokers(int num) {
        for (int i = 0; i < num; i++) {
            Worker worker = new Worker();
            workers.add(worker);
            Thread thread = new Thread(worker, "ThreadPool-Worker-" + threadNum.incrementAndGet());
            thread.start();
        }
    }

    @Override
    public void removeWorkers(int num) {

        synchronized (jobs) {
            if (num > this.workerNum) {
                throw new IllegalArgumentException("beyond workNum");
            }
            int count = 0;
            while (count < num) {
                Worker worker = workers.get(count);
                if (workers.remove(worker)) {
                    worker.shutdown();
                    count++;
                }
            }

        }

    }

    @Override
    public int getJobSize() {
        return jobs.size();
    }


    public class Worker implements Runnable {
        private volatile boolean running = true;
        @Override
        public void run() {
            while (running) {
                Job job = null;
                synchronized (jobs) {
                    while (jobs.isEmpty()) {
                        try {
                            System.out.println("工作初始化:"+ Thread.currentThread().getName());
                            jobs.wait();
                        } catch (InterruptedException e) {
                            //wait被中断异常,直接终止线程返回
                            Thread.currentThread().interrupt();
                            return;
                        }
                    }
                    job = jobs.removeFirst();
                    System.out.println(job);
                }
                if (job != null) {
                    job.run();
                }
            }
            System.out.println("线程已停止!");
        }
        public void shutdown() {
            running = false;
        }
    }

}
